<template>
  <div>
    <div class="content">
      <canvas ref="canvasRef"></canvas>
    </div>
    <div class="fixed">
      <div>
        <img
          @click="handleSetting"
          class="img"
          src="@/assets/setting.png"
          alt=""
        />
      </div>
      <div>
        <img @click="download" class="img" src="@/assets/download.png" alt="" />
      </div>
      <div>
        <img @click="reset" class="img" src="@/assets/reload.png" alt="" />
      </div>
      <div class="color-list" @click="handleChangeColor()">
        <div
          class="bg-color"
          :style="{ background: currentColor2, zIndex: isFirst ? 1 : 2 }"
        ></div>
        <div
          class="bg-color"
          :style="{ background: currentColor1, zIndex: isFirst ? 2 : 1 }"
        ></div>
      </div>
      <div>
        <img @click="back" class="img" src="@/assets/back.png" alt="" />
      </div>
    </div>
    <div class="picture" v-if="downloadShow" @click="downloadShow = false">
      <div>
        <img :src="src" alt="" />
        <div class="text">长按图片保存到手机</div>
      </div>
    </div>
    <!-- 新增的气泡框 -->
    <div
      v-if="showBubble && peopleShow"
      class="bubble"
      :style="{ top: bubbleTop + 'px', left: bubbleLeft + 'px' }"
    >
      <div class="tooltips" @click="handlePelpleCHange">
        <div class="tooltips-content">换形象</div>
      </div>
    </div>
    <div class="modals" v-if="show" @click="closeModals">
      <div class="modals-content" @click.stop>
        <div class="modals-header">
          <div class="lll">
            <img
              style="visibility: hidden"
              class="close"
              src="@/assets/close.png"
              alt=""
            />
            <div class="setting">设置</div>
            <img
              class="close"
              @click="closeModals"
              src="@/assets/close.png"
              alt=""
            />
          </div>
        </div>
        <div class="modals-body">
          <div style="margin-top: 14px">
            <div class="title">单双打：</div>
            <div class="rows">
              <div class="rows-item" @click="handlePeoPleNumber('single')">
                <div
                  class="circle"
                  :class="{ active: singlesAndDoubles == 'single' }"
                ></div>
                <div class="text">单打</div>
              </div>
              <div
                class="rows-item"
                style="margin-left: 20px"
                @click="handlePeoPleNumber('double')"
              >
                <div
                  class="circle"
                  :class="{ active: singlesAndDoubles == 'double' }"
                ></div>
                <div class="text">双打</div>
              </div>
            </div>
          </div>
          <div style="margin-top: 14px">
            <div class="title">线粗细：</div>
            <div class="rows">
              <div
                class="rows-item"
                v-for="item in lineWidths"
                :key="item"
                @click="lineWidth = item"
              >
                <div class="line" :class="{ active: item == lineWidth }">
                  <div
                    class="dot"
                    :style="{
                      width: item + 'px',
                      height: item + 'px',
                    }"
                  ></div>
                </div>
              </div>
            </div>
          </div>
          <div style="margin-top: 14px">
            <div class="title">线颜色：</div>
            <div class="rows">
              <div class="rows-item">
                <!-- <input  class="inp" type="color" /> -->
                <div class="custom-color-picker1">
                  <input
                    onchange="this.parentElement.style.backgroundColor = this.value;"
                    type="color"
                    v-model="currentColor1"
                  />
                </div>
                <div class="text">色1</div>
              </div>
              <div class="rows-item" style="margin-left: 20px">
                <div class="custom-color-picker2">
                  <input
                    onchange="this.parentElement.style.backgroundColor = this.value;"
                    type="color"
                    v-model="currentColor2"
                  />
                </div>
                <div class="text">色2</div>
              </div>
            </div>
          </div>
          <div style="margin-top: 14px">
            <div class="title">场地背景：</div>
            <div class="rows">
              <div class="rows-item" @click="handleChangeBg('red')">
                <img
                  :src="red_court_img"
                  alt=""
                  class="bg-img"
                  :class="{ active: currentBg === 'red' }"
                />
              </div>
              <div
                class="rows-item"
                style="margin-left: 20px"
                @click="handleChangeBg('blue')"
              >
                <img
                  :src="hard_court_img"
                  alt=""
                  class="bg-img"
                  :class="{ active: currentBg === 'blue' }"
                />
              </div>
              <div
                class="rows-item"
                style="margin-left: 20px"
                @click="handleChangeBg('green')"
              >
                <img
                  :src="grass_court_img"
                  alt=""
                  class="bg-img"
                  :class="{ active: currentBg === 'green' }"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div
      class="modals"
      v-if="showPeople1 && showBubble1"
      @click="closePeopleModals"
    >
      <div class="modals-content" @click.stop>
        <div class="modals-header">
          <div class="lll">
            <img
              style="visibility: hidden"
              class="close"
              src="@/assets/close.png"
              alt=""
            />
            <div class="setting">换形象</div>
            <img
              class="close"
              @click="closePeopleModals"
              src="@/assets/close.png"
              alt=""
            />
          </div>
        </div>
        <div class="modals-body">
          <div>
            <div class="people-title">男生：</div>
            <div class="players">
              <div
                class="player-bg"
                :class="{ active: gender == 'n' && peopleIdx == 1 }"
                @click="handleChangePeople('n', 1)"
              >
                <img class="player" :src="player_opponent_img_n_1" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'n' && peopleIdx == 2 }"
                @click="handleChangePeople('n', 2)"
              >
                <img class="player" :src="player_opponent_img_n_2" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'n' && peopleIdx == 3 }"
                @click="handleChangePeople('n', 3)"
              >
                <img class="player" :src="player_opponent_img_n_3" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'n' && peopleIdx == 4 }"
                @click="handleChangePeople('n', 4)"
              >
                <img class="player" :src="player_opponent_img_n_4" alt="" />
              </div>
            </div>
          </div>
          <div>
            <div class="people-title">女生：</div>
            <div class="players">
              <div
                class="player-bg"
                :class="{ active: gender == 'w' && peopleIdx == 1 }"
                @click="handleChangePeople('w', 1)"
              >
                <img class="player" :src="player_opponent_img_w_1" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'w' && peopleIdx == 2 }"
                @click="handleChangePeople('w', 2)"
              >
                <img class="player" :src="player_opponent_img_w_2" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'w' && peopleIdx == 3 }"
                @click="handleChangePeople('w', 3)"
              >
                <img class="player" :src="player_opponent_img_w_3" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'w' && peopleIdx == 4 }"
                @click="handleChangePeople('w', 4)"
              >
                <img class="player" :src="player_opponent_img_w_4" alt="" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      class="modals"
      v-if="showPeople2 && showBubble2"
      @click="closePeopleModals"
    >
      <div class="modals-content" @click.stop>
        <div class="modals-header">
          <div class="lll">
            <img
              style="visibility: hidden"
              class="close"
              src="@/assets/close.png"
              alt=""
            />
            <div class="setting">换形象</div>
            <img
              class="close"
              @click="closePeopleModals"
              src="@/assets/close.png"
              alt=""
            />
          </div>
        </div>
        <div class="modals-body">
          <div>
            <div class="people-title">男生：</div>
            <div class="players">
              <div
                class="player-bg"
                :class="{ active: gender == 'n' && peopleIdx == 1 }"
                @click="handleChangePeople('n', 1)"
              >
                <img class="player" :src="player_me_img_n_1" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'n' && peopleIdx == 2 }"
                @click="handleChangePeople('n', 2)"
              >
                <img class="player" :src="player_me_img_n_2" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'n' && peopleIdx == 3 }"
                @click="handleChangePeople('n', 3)"
              >
                <img class="player" :src="player_me_img_n_3" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'n' && peopleIdx == 4 }"
                @click="handleChangePeople('n', 4)"
              >
                <img class="player" :src="player_me_img_n_4" alt="" />
              </div>
            </div>
          </div>
          <div>
            <div class="people-title">女生：</div>
            <div class="players">
              <div
                class="player-bg"
                :class="{ active: gender == 'w' && peopleIdx == 1 }"
                @click="handleChangePeople('w', 1)"
              >
                <img class="player" :src="player_me_img_w_1" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'w' && peopleIdx == 2 }"
                @click="handleChangePeople('w', 2)"
              >
                <img class="player" :src="player_me_img_w_2" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'w' && peopleIdx == 3 }"
                @click="handleChangePeople('w', 3)"
              >
                <img class="player" :src="player_me_img_w_3" alt="" />
              </div>
              <div
                class="player-bg"
                :class="{ active: gender == 'w' && peopleIdx == 4 }"
                @click="handleChangePeople('w', 4)"
              >
                <img class="player" :src="player_me_img_w_4" alt="" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, nextTick } from "vue";
// import player_opponent_img from "@/assets/player_duishou.png";
// import player_me_img from "@/assets/player_me.png";
// import red_court_img from "@/assets/court_red.png";
// import hard_court_img from "@/assets/court_blue.png";
// import grass_court_img from "@/assets/court_green.png";
// import player_opponent_img_n_1 from "@/assets/n_y1.png";
// import player_opponent_img_n_2 from "@/assets/n_y2.png";
// import player_opponent_img_n_3 from "@/assets/n_y3.png";
// import player_opponent_img_n_4 from "@/assets/n_y4.png";
// import player_opponent_img_w_1 from "@/assets/g_y1.png";
// import player_opponent_img_w_2 from "@/assets/g_y2.png";
// import player_opponent_img_w_3 from "@/assets/g_y3.png";
// import player_opponent_img_w_4 from "@/assets/g_y4.png";

// import player_me_img_n_1 from "@/assets/n_m1.png";
// import player_me_img_n_2 from "@/assets/n_m2.png";
// import player_me_img_n_3 from "@/assets/n_m3.png";
// import player_me_img_n_4 from "@/assets/n_m4.png";
// import player_me_img_w_1 from "@/assets/g_m1.png";
// import player_me_img_w_2 from "@/assets/g_m2.png";
// import player_me_img_w_3 from "@/assets/g_m3.png";
// import player_me_img_w_4 from "@/assets/g_m4.png";
// import { Player } from "./element/player";

const baseUrl =
  "https://ykx-1254116920.cos.ap-nanjing.myqcloud.com/tenniswhiteboard";

const player_opponent_img = ref(`${baseUrl}/boy1_front.png`);
const player_me_img = ref(`${baseUrl}/boy1_front.png`);
const red_court_img = ref(`${baseUrl}/court_red.png`);
const hard_court_img = ref(`${baseUrl}/court_blue.png`);
const grass_court_img = ref(`${baseUrl}/court_green.png`);
const player_opponent_img_n_1 = ref(`${baseUrl}/boy1_front.png`);
const player_opponent_img_n_2 = ref(`${baseUrl}/boy2_front.png`);
const player_opponent_img_n_3 = ref(`${baseUrl}/boy3_front.png`);
const player_opponent_img_n_4 = ref(`${baseUrl}/boy4_front.png`);
const player_opponent_img_w_1 = ref(`${baseUrl}/girl1_front.png`);
const player_opponent_img_w_2 = ref(`${baseUrl}/girl2_front.png`);
const player_opponent_img_w_3 = ref(`${baseUrl}/girl3_front.png`);
const player_opponent_img_w_4 = ref(`${baseUrl}/girl4_front.png`);

const player_me_img_n_1 = ref(`${baseUrl}/boy1_back.png`);
const player_me_img_n_2 = ref(`${baseUrl}/boy2_back.png`);
const player_me_img_n_3 = ref(`${baseUrl}/boy3_back.png`);
const player_me_img_n_4 = ref(`${baseUrl}/boy4_back.png`);
const player_me_img_w_1 = ref(`${baseUrl}/girl1_back.png`);
const player_me_img_w_2 = ref(`${baseUrl}/girl2_back.png`);
const player_me_img_w_3 = ref(`${baseUrl}/girl3_back.png`);
const player_me_img_w_4 = ref(`${baseUrl}/girl4_back.png`);
import { Player } from "./element/player";

const canvasRef = ref<HTMLCanvasElement | null>(null);
const downloadShow = ref(false);
const peopleChangeShow = ref(false);
const src = ref("");
const drawings = ref<
  Array<{ x: number; y: number; color: string; lineWidth: number }[]>
>([]);
const playerPositions = ref<{
  opponent: { x: number; y: number }[];
  opponent1: { x: number; y: number }[];
  me: { x: number; y: number }[];
  me1: { x: number; y: number }[];
}>({
  opponent: [],
  opponent1: [],
  me: [],
  me1: [],
});

const show = ref(false);
const showPeople1 = ref(false);
const showPeople2 = ref(false);
const screenWidth = document.body?.clientWidth * 2 || window?.innerWidth * 2;
const screenHeight = document.body?.clientHeight * 2 || window?.innerHeight * 2;
console.log(screenWidth, screenHeight, 11111111111);
/**
 * 初始化位置
 */
//对手1
const initPostionOpponentTop = ref(80);
const initPostionOpponentLeft = ref(130); //从左边开始计算
//对手2
const initPostionOpponent1Top = ref(240);
const initPostionOpponent1Left = ref(150); //从右边计算
//自己1
const initPostionMeTop = ref(50);
const initPostionMeLeft = ref(120); //从右边开始计算
//自己2
const initPostionMe1Top = ref(250);
const initPostionMe1Left = ref(120); //从左边开始计算

const imageUrlsInit = ref([
  red_court_img.value,
  player_opponent_img_n_3.value,
  player_opponent_img_w_3.value,
  player_me_img_w_1.value,
  player_me_img_n_1.value,
]);

const imageUrls = ref([
  red_court_img.value,
  player_opponent_img.value,
  player_me_img.value,
  hard_court_img.value,
  grass_court_img.value,
  player_opponent_img_n_1.value,
  player_opponent_img_n_2.value,
  player_opponent_img_n_3.value,
  player_opponent_img_n_4.value,
  player_opponent_img_w_1.value,
  player_opponent_img_w_2.value,
  player_opponent_img_w_3.value,
  player_opponent_img_w_4.value,
  player_me_img_n_1.value,
  player_me_img_n_2.value,
  player_me_img_n_3.value,
  player_me_img_n_4.value,
  player_me_img_w_1.value,
  player_me_img_w_2.value,
  player_me_img_w_3.value,
  player_me_img_w_4.value,
]);

const allImgs = ref([]);
const manImgs = ref({
  y: [],
  m: [],
});
const womanImgs = ref({
  y: [],
  m: [],
});

const lineWidths = ref<number[]>([2, 4, 6, 8]);

const isFirst = ref(true);
const currentColor1 = ref("#5EEE3A");
const currentColor2 = ref("#FF7CFB");
const currentColor = ref(currentColor1.value);

const lineWidth = ref<number>(4);
const currentBg = ref("red");
const singlesAndDoubles = ref<"single" | "double">("double");

const currentPath = ref<
  Array<{ x: number; y: number; color: string; lineWidth: number }>
>([]);
let isDrawing = false;
let isPlayOpponentDragging = false;
let isPlayOpponentDragging1 = false;
let isPlayMeDragging = false;
let isPlayMeDragging1 = false;

const backgroundImage = ref(red_court_img.value);
const playerOpponent = ref();
const playerOpponent1 = ref();
const playerMe = ref();
const playerMe1 = ref();

type Operation = {
  type: "draw" | "movePlayer";
  data: any;
};

const operations = ref<Operation[]>([]);

// 换形象
const showBubble = ref(false);
const showBubble1 = ref(false);
const showBubble2 = ref(false);
const bubbleTop = ref(0);
const bubbleLeft = ref(0);
const bubbleNum = ref("");
const peopleIdx = ref(0);
const gender = ref("n");

async function initializeCanvas() {
  const canvas = canvasRef.value!;
  canvas.width = screenWidth;
  canvas.height = screenHeight;
  const ctx = canvas.getContext("2d")!;

  loadImages(imageUrlsInit.value).then((images) => {
    const [
      redCourtImage,
      player_opponent_img_n_1,
      player_opponent_img_n_2,
      player_me_img_n_1,
      player_me_img_n_2,
    ] = images;
    allImgs.value = {
      redCourtImage,
      player_opponent_img_n_1,
      player_opponent_img_n_2,
      player_me_img_n_1,
      player_me_img_n_2,
    };

    backgroundImage.value = redCourtImage;
    playerOpponent.value = new Player(
      initPostionOpponentLeft.value * 2,
      initPostionOpponentTop.value * 2,
      player_opponent_img_n_1,
      1
    );
    playerMe.value = new Player(
      screenWidth - initPostionMeLeft.value * 2,
      screenHeight - initPostionMeTop.value * 2 - 200 * 2,
      player_me_img_n_2,
      2
    );
    // console.log(playerMe.value);
    playerOpponent1.value = new Player(
      screenWidth - initPostionOpponent1Left.value * 2,
      initPostionOpponent1Top.value * 2,
      player_opponent_img_n_2,
      1
    );
    playerMe1.value = new Player(
      initPostionMe1Left.value * 2,
      screenHeight - initPostionMe1Top.value * 2 - 200 * 2,
      player_me_img_n_1,
      2
    );

    addEventListeners(canvas, ctx);
    redraw(ctx);

    loadImages(imageUrls.value).then((images) => {
      const [
        redCourtImage,
        playerOpponentImg,
        playerMeImg,
        hardCourtImage,
        grassCourtImage,
        player_opponent_img_n_1,
        player_opponent_img_n_2,
        player_opponent_img_n_3,
        player_opponent_img_n_4,
        player_opponent_img_w_1,
        player_opponent_img_w_2,
        player_opponent_img_w_3,
        player_opponent_img_w_4,
        player_me_img_n_1,
        player_me_img_n_2,
        player_me_img_n_3,
        player_me_img_n_4,
        player_me_img_w_1,
        player_me_img_w_2,
        player_me_img_w_3,
        player_me_img_w_4,
      ] = images;

      allImgs.value = {
        redCourtImage,
        playerOpponentImg,
        playerMeImg,
        hardCourtImage,
        grassCourtImage,
        player_opponent_img_n_1,
        player_opponent_img_n_2,
        player_opponent_img_n_3,
        player_opponent_img_n_4,
        player_opponent_img_w_1,
        player_opponent_img_w_2,
        player_opponent_img_w_3,
        player_opponent_img_w_4,
        player_me_img_n_1,
        player_me_img_n_2,
        player_me_img_n_3,
        player_me_img_n_4,
        player_me_img_w_1,
        player_me_img_w_2,
        player_me_img_w_3,
        player_me_img_w_4,
      };

      const n = [
        player_opponent_img_n_1,
        player_opponent_img_n_2,
        player_opponent_img_n_3,
        player_opponent_img_n_4,
      ];
      const n1 = [
        player_me_img_n_1,
        player_me_img_n_2,
        player_me_img_n_3,
        player_me_img_n_4,
      ];
      manImgs.value.y = n;
      manImgs.value.m = n1;

      const w = [
        player_opponent_img_w_1,
        player_opponent_img_w_2,
        player_opponent_img_w_3,
        player_opponent_img_w_4,
      ];
      const w1 = [
        player_me_img_w_1,
        player_me_img_w_2,
        player_me_img_w_3,
        player_me_img_w_4,
      ];
      womanImgs.value.y = w;
      womanImgs.value.m = w1;
    });
  });
}

// 预加载图像
function preloadImages(urls: string[]): Promise<HTMLImageElement[]> {
  return new Promise((resolve, reject) => {
    const images = urls.map((url) => {
      const img = new Image();
      img.src = url;
      img.onload = () => {
        if (--urls.length === 0) {
          resolve(images);
        }
      };
      img.onerror = () => {
        reject(new Error(`Failed to load image at ${url}`));
      };
      return img;
    });
  });
}

function loadImages(urls: string[]) {
  return new Promise<HTMLImageElement[]>((resolve, reject) => {
    const images = urls.map((url) => {
      const img = new Image();
      img.src = url + "?t=" + new Date().getTime();
      img.crossOrigin = "Anonymous";
      // console.log(img, "imgimg");
      // img.setAttribute("crossOrigin", "anonymous");
      return img;
    });
    let loadedCount = 0;
    images.forEach((img, index) => {
      img.onload = () => {
        loadedCount++;

        if (loadedCount === urls.length) {
          resolve(images);
        }
      };
      img.onerror = (err) => {
        console.log(`Image failed to load: ${urls[index]}`, index);
        console.log(urls, "urlsurlsurlsurlsurls");
      };
    });
  });
}
window.onerror = (message, source, lineno, colno, error) => {
  console.error("页面错误：", { message, source, lineno, colno, error });
};
function addEventListeners(
  canvas: HTMLCanvasElement,
  ctx: CanvasRenderingContext2D
) {
  canvas.addEventListener("touchstart", (e) => handleTouchStart(e, ctx));
  canvas.addEventListener("touchmove", (e) => handleTouchMove(e, ctx));
  canvas.addEventListener("touchend", () => handleTouchEnd(ctx));
  document.addEventListener("click", hideBubble); // 添加点击其他地方隐藏气泡框的事件
}

const peopleShow = ref(false);
function handleClick() {
  peopleShow.value = true;
}

let touchStartTime = 0; // 记录触摸开始时间
const maxTouchTime = 150; // 最大点击时间（毫秒）

function handleTouchStart(e: TouchEvent, ctx: CanvasRenderingContext2D) {
  touchStartTime = Date.now();
  // hideBubble();
  e.preventDefault();
  const touchPos = getTouchPos(canvasRef.value!, e.touches[0]);
  const canvasRect = canvasRef.value!.getBoundingClientRect();
  if (playerOpponent.value.isInsideImage(touchPos)) {
    isPlayOpponentDragging = true;
    playerOpponent.value.setOffset(
      touchPos.x * 2 - playerOpponent.value.x,
      touchPos.y * 2 - playerOpponent.value.y
    );
    playerOpponent.value.recordStartPosition(); // 记录起始点
    showBubble.value = true;
    showBubble1.value = true;
    showBubble2.value = false;
    bubbleNum.value = 1;
    bubbleTop.value =
      playerOpponent.value.y / 2 - playerOpponent.value.image.height / 32; // 气泡框的位置
    bubbleLeft.value = playerOpponent.value.x / 2 + canvasRect.left + 25; // 气泡框的位置
  } else if (
    singlesAndDoubles.value == "double" &&
    playerOpponent1.value.isInsideImage(touchPos)
  ) {
    isPlayOpponentDragging1 = true;
    playerOpponent1.value.setOffset(
      touchPos.x * 2 - playerOpponent1.value.x,
      touchPos.y * 2 - playerOpponent1.value.y
    );
    playerOpponent1.value.recordStartPosition(); // 记录起始点
    showBubble.value = true;
    showBubble1.value = true;
    showBubble2.value = false;
    bubbleNum.value = 2;
    bubbleTop.value =
      playerOpponent1.value.y / 2 - playerOpponent1.value.image.height / 32; // 气泡框的位置
    bubbleLeft.value = playerOpponent1.value.x / 2 + canvasRect.left + 25; // 气泡框的位置
  } else if (playerMe.value.isInsideImage(touchPos)) {
    isPlayMeDragging = true;
    playerMe.value.setOffset(
      touchPos.x * 2 - playerMe.value.x,
      touchPos.y * 2 - playerMe.value.y
    );
    playerMe.value.recordStartPosition(); // 记录起始点
    showBubble.value = true;
    showBubble2.value = true;
    showBubble1.value = false;
    bubbleNum.value = 3;
    bubbleTop.value =
      playerMe.value.y / 2 -
      playerOpponent.value.image.height / 32 +
      canvasRect.top; // 气泡框的位置
    bubbleLeft.value = playerMe.value.x / 2 + canvasRect.left + 28; // 气泡框的位置
  } else if (
    singlesAndDoubles.value == "double" &&
    playerMe1.value.isInsideImage(touchPos)
  ) {
    isPlayMeDragging1 = true;
    playerMe1.value.setOffset(
      touchPos.x * 2 - playerMe1.value.x,
      touchPos.y * 2 - playerMe1.value.y
    );
    playerMe1.value.recordStartPosition(); // 记录起始点
    showBubble.value = true;
    showBubble2.value = true;
    showBubble1.value = false;
    bubbleNum.value = 4;
    bubbleTop.value =
      playerMe1.value.y / 2 -
      playerMe1.value.image.height / 32 +
      canvasRect.top; // 气泡框的位置
    bubbleLeft.value = playerMe1.value.x / 2 + canvasRect.left + 28; // 气泡框的位置
  } else {
    isDrawing = true;
    currentPath.value = [];
    const color = currentColor.value;
    currentPath.value.push({
      x: touchPos.x * 2,
      y: touchPos.y * 2,
      color: color,
      lineWidth: lineWidth.value * 2,
    });
  }
}

function handleTouchMove(e: TouchEvent, ctx: CanvasRenderingContext2D) {
  e.preventDefault();
  hideBubble();

  const touchPos = getTouchPos(canvasRef.value!, e.touches[0]);

  if (isPlayOpponentDragging) {
    playerOpponent.value.refreshXY(touchPos);
    redraw(ctx);
  } else if (singlesAndDoubles.value == "double" && isPlayOpponentDragging1) {
    playerOpponent1.value.refreshXY(touchPos);
    redraw(ctx);
  } else if (isPlayMeDragging) {
    playerMe.value.refreshXY(touchPos);
    redraw(ctx);
  } else if (singlesAndDoubles.value == "double" && isPlayMeDragging1) {
    playerMe1.value.refreshXY(touchPos);
    redraw(ctx);
  } else if (isDrawing) {
    currentPath.value.push({
      x: touchPos.x * 2,
      y: touchPos.y * 2,
      color: currentPath.value[0].color,
      lineWidth: currentPath.value[0].lineWidth * 2,
    });

    const lastPoint = currentPath.value[currentPath.value.length - 2];
    const currentPoint = currentPath.value[currentPath.value.length - 1];
    ctx.strokeStyle = currentPath.value[0].color;
    ctx.lineWidth = currentPath.value[0].lineWidth;
    ctx.beginPath();
    ctx.moveTo(lastPoint.x, lastPoint.y);
    ctx.lineTo(currentPoint.x, currentPoint.y);
    ctx.stroke();
  }
}

function handleTouchEnd(ctx: CanvasRenderingContext2D) {
  const touchEndTime = Date.now();
  const elapsedTime = touchEndTime - touchStartTime;
  // 判断是否是点击事件
  if (elapsedTime <= maxTouchTime && touchStartTime !== 0) {
    console.log("点击事件触发");
    handleClick(); // 调用点击处理函数
  }
  ctx.closePath();

  if (currentPath.value.length > 0) {
    drawings.value.push([...currentPath.value]);
    operations.value.push({ type: "draw", data: [...currentPath.value] });
  }

  // 记录人物位置
  if (isPlayOpponentDragging) {
    operations.value.push({
      type: "movePlayer",
      data: {
        player: "opponent",
        x: playerOpponent.value.x,
        y: playerOpponent.value.y,
      },
    });
    playerPositions.value.opponent.push({
      x: playerOpponent.value.x,
      y: playerOpponent.value.y,
    });
  } else if (isPlayOpponentDragging1) {
    operations.value.push({
      type: "movePlayer",
      data: {
        player: "opponent1",
        x: playerOpponent1.value.x,
        y: playerOpponent1.value.y,
      },
    });
    if (singlesAndDoubles.value == "double") {
      playerPositions.value.opponent1.push({
        x: playerOpponent1.value.x,
        y: playerOpponent1.value.y,
      });
    }
  } else if (isPlayMeDragging) {
    operations.value.push({
      type: "movePlayer",
      data: { player: "me", x: playerMe.value.x, y: playerMe.value.y },
    });
    playerPositions.value.me.push({
      x: playerMe.value.x,
      y: playerMe.value.y,
    });
  } else if (isPlayMeDragging1) {
    operations.value.push({
      type: "movePlayer",
      data: {
        player: "me1",
        x: playerMe1.value.x,
        y: playerMe1.value.y,
      },
    });
    if (singlesAndDoubles.value == "double") {
      playerPositions.value.me1.push({
        x: playerMe1.value.x,
        y: playerMe1.value.y,
      });
    }
  }
  isDrawing = false;
  isPlayMeDragging = false;
  isPlayOpponentDragging = false;
  isPlayOpponentDragging1 = false;
  isPlayMeDragging1 = false;
  // 清空当前路径
  currentPath.value = [];

  redraw(ctx);
}
function redraw(ctx: CanvasRenderingContext2D) {
  ctx.clearRect(0, 0, screenWidth, screenHeight);

  ctx.drawImage(backgroundImage.value, 0, 0, screenWidth, screenHeight);
  playerOpponent.value.draw(ctx);
  playerMe.value.draw(ctx);
  if (singlesAndDoubles.value == "double") {
    playerOpponent1.value.draw(ctx);
    playerMe1.value.draw(ctx);
  }

  drawings.value.forEach((path) => {
    ctx.strokeStyle = path[0].color;
    ctx.lineWidth = path[0].lineWidth;

    for (let i = 1; i < path.length; i++) {
      ctx.beginPath();
      ctx.moveTo(path[i - 1].x, path[i - 1].y);
      ctx.lineTo(path[i].x, path[i].y);
      ctx.stroke();
    }
  });
}

function getTouchPos(canvas: HTMLCanvasElement, touch: Touch) {
  const rect = canvas.getBoundingClientRect();
  return { x: touch.clientX - rect.left, y: touch.clientY - rect.top };
}

function download() {
  const canvas = canvasRef.value!;
  const dataURL = canvas.toDataURL("image/png");
  console.log(dataURL);
  src.value = dataURL;
  downloadShow.value = true;
}

function back() {
  if (operations.value.length === 0) return;
  const lastOperation = operations.value.pop();

  if (lastOperation.type === "draw") {
    drawings.value.pop();
  } else if (lastOperation.type === "movePlayer") {
    const player = lastOperation.data.player;
    console.log(player, "playerplayer");
    let positions;
    if (player === "opponent") {
      positions = playerPositions.value.opponent;
    } else if (player === "me") {
      positions = playerPositions.value.me;
    } else if (player === "opponent1") {
      positions = playerPositions.value.opponent1;
    } else if (player === "me1") {
      positions = playerPositions.value.me1;
    }
    positions.pop();
    if (positions.length > 0) {
      const lastPosition = positions[positions.length - 1];
      if (player === "opponent") {
        playerOpponent.value.x = lastPosition.x;
        playerOpponent.value.y = lastPosition.y;
      } else if (player === "opponent1") {
        playerOpponent1.value.x = lastPosition.x;
        playerOpponent1.value.y = lastPosition.y;
      } else if (player === "me") {
        playerMe.value.x = lastPosition.x;
        playerMe.value.y = lastPosition.y;
      } else if (player === "me1") {
        playerMe1.value.x = lastPosition.x;
        playerMe1.value.y = lastPosition.y;
      }
    } else {
      console.log("重置");
      if (player === "opponent") {
        console.log(1);
        playerOpponent.value.restInitPosition();
      } else if (player === "opponent1") {
        console.log(2);
        playerOpponent1.value.restInitPosition();
      } else if (player === "me") {
        console.log(3);
        playerMe.value.restInitPosition();
      } else if (player === "me1") {
        console.log(4);
        playerMe1.value.restInitPosition();
      }
    }
  }

  const ctx = canvasRef.value!.getContext("2d")!;
  redraw(ctx);
}

//重置炒作
function reset() {
  drawings.value = [];
  playerPositions.value = { opponent: [], me: [], me1: [], opponent1: [] };
  operations.value = [];
  currentPath.value = [];

  if (singlesAndDoubles.value == "double") {
    playerMe1.value.restInitPosition();
    playerOpponent1.value.restInitPosition();
  }
  playerMe.value.restInitPosition();
  playerOpponent.value.restInitPosition();

  const ctx = canvasRef.value!.getContext("2d")!;
  showBubble.value = false;
  redraw(ctx);
}

function hideBubble() {
  showBubble.value = false;
  peopleShow.value = false;
}

function handleSetting() {
  show.value = true;
}

function closeModals() {
  show.value = false;
}
function closePeopleModals() {
  showPeople1.value = false;
  showPeople2.value = false;
  peopleIdx.value = 0;
}

function handleChangeBg(bg: string) {
  currentBg.value = bg;
  if (bg == "red") {
    backgroundImage.value = allImgs.value.redCourtImage;
  } else if (bg == "blue") {
    backgroundImage.value = allImgs.value.hardCourtImage;
  } else if (bg == "green") {
    backgroundImage.value = allImgs.value.grassCourtImage;
  }
  redraw(canvasRef.value!.getContext("2d")!);
}

function handlePeoPleNumber(num: "single" | "double") {
  singlesAndDoubles.value = num;
  // const ctx = canvasRef.value!.getContext("2d")!;

  reset();
}

function handleChangeColor() {
  isFirst.value = !isFirst.value;
  if (isFirst.value) {
    currentColor.value = currentColor1.value;
  } else {
    currentColor.value = currentColor2.value;
  }
}

function handlePelpleCHange() {
  showPeople1.value = true;
  showPeople2.value = true;
  showBubble.value = false;
  peopleShow.value = false;
}

function handleChangePeople(type, idx) {
  gender.value = type;
  peopleIdx.value = idx;
  if (bubbleNum.value == 1 && type == "n") {
    playerOpponent.value.changeImage(manImgs.value.y[peopleIdx.value - 1]);
  }
  if (bubbleNum.value == 1 && type == "w") {
    playerOpponent.value.changeImage(womanImgs.value.y[peopleIdx.value - 1]);
  }
  if (bubbleNum.value == 2 && type == "n") {
    playerOpponent1.value.changeImage(manImgs.value.y[peopleIdx.value - 1]);
  }
  if (bubbleNum.value == 2 && type == "w") {
    playerOpponent1.value.changeImage(womanImgs.value.y[peopleIdx.value - 1]);
  }
  if (bubbleNum.value == 3 && type == "n") {
    playerMe.value.changeImage(manImgs.value.m[peopleIdx.value - 1]);
  }
  if (bubbleNum.value == 3 && type == "w") {
    playerMe.value.changeImage(womanImgs.value.m[peopleIdx.value - 1]);
  }
  if (bubbleNum.value == 4 && type == "w") {
    playerMe1.value.changeImage(womanImgs.value.m[peopleIdx.value - 1]);
  }
  if (bubbleNum.value == 4 && type == "n") {
    playerMe1.value.changeImage(manImgs.value.m[peopleIdx.value - 1]);
  }
  const ctx = canvasRef.value!.getContext("2d")!;
  redraw(ctx);
}

watch(
  () => currentColor1.value,
  () => {
    currentColor.value = currentColor1.value;
  },
  {
    deep: true,
  }
);
watch(
  () => currentColor2.value,
  () => {
    currentColor.value = currentColor2.value;
  },
  {
    deep: true,
  }
);

onMounted(() => {
  nextTick(() => {
    initializeCanvas();
  });
});
</script>

<style lang="scss">
body,
html {
  margin: 0;
  padding: 0;
}
.content {
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.operation_container {
  padding: 50px;
  display: flex;
  flex-direction: column;
  position: fixed;
  bottom: 0;
  left: 0;
}
.fixed {
  position: fixed;
  padding: 24px;
  bottom: 0px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .img {
    width: 32px;
    height: 32px;
  }
}
.picture {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  > div {
    transform: scale(0.71) translateY(-100px);
    .text {
      color: #fff;
      font-size: 24px;
      text-align: center;
      margin-top: 20px;
    }
  }
  img {
    width: 100%;
    object-fit: cover;
  }
}
.bubble {
  position: absolute;
  border-radius: 5px;
  z-index: 1000;
}
.tooltips {
  position: relative;
  display: inline-block;
}
.tooltips-content {
  width: 58px;
  height: 26px;
  line-height: 26px;
  background: #ffffff;
  border-radius: 4px 4px 4px 4px;
  text-align: center;
  font-size: 14px;
  border-radius: 5px;
  position: absolute;
  bottom: 125%; /* 距离触发点的距离 */
  left: 50%;
  transform: translateX(-50%);
  z-index: 1;
  /* 添加小箭头 */
}
.tooltips-content::after {
  content: "";
  position: absolute;
  top: 100%; /* 小箭头定位在气泡框下边缘 */
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #fff transparent transparent transparent;
}

.modals {
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: flex-end;
  justify-content: center;
  transition: all 0.3s ease;
}

.modals-content {
  background-color: #fefefe;
  width: 100%;
  animation: slide-up 0.3s forwards;
  border-radius: 10px 10px 0 0;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
  position: relative;
}

@keyframes slide-up {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.modals-header {
  padding: 16px 16px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  .lll {
    border-bottom: 1px solid #e9e9e9;
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    padding-bottom: 13px;
    .setting {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 18px;
      color: #4d4d4d;
      line-height: 28px;
      text-align: center;
      font-style: normal;
      text-transform: none;
    }
    .close {
      width: 32px;
      height: 32px;
    }
  }
}

.modals-body {
  padding: 0px 17px 20px;
  .people-title {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 16px;
    color: #4d4d4d;
    padding: 17px 0 14px;
  }
  .players {
    display: flex;
    justify-content: space-between;
    .player-bg {
      width: 72px;
      height: 100px;
      background: #d9d9d9;
      border-radius: 8px 8px 8px 8px;
      display: flex;
      justify-content: center;
      align-items: center;
      &.active {
        border: #2c70e5 3px solid;
      }
    }
    .player {
      object-fit: cover;
      width: 59px;
      height: 84px;
      border-radius: 5px;
    }
  }
  .title {
    font-weight: 400;
    font-size: 16px;
    color: #828282;
    line-height: 28px;
    text-align: left;
  }
  .rows {
    display: flex;
    align-items: center;
    .rows-item {
      display: flex;
      align-items: center;
      position: relative;
    }
    .inp {
      width: 25px;
      height: 25px;
      border-radius: 50%;
      border: 2px solid rgba(255, 255, 255, 0.84);
    }
    .inp2 {
      width: 25px;
      height: 25px;
      background: #e5e5e5;
      border: 2px solid rgba(255, 255, 255, 0.84);
      border-radius: 50%;
      position: relative;
      overflow: hidden;
      &::after {
        content: "";
        position: absolute;
        width: 2px;
        height: 100%;
        left: 50%;
        transform: translateX(-50%) rotate(45deg);
        background-color: rgba(192, 192, 192, 0.84);
      }
    }
    .circle {
      width: 18px;
      height: 18px;
      background: #d9d9d9;
      border-radius: 0px 0px 0px 0px;
      border: 1px solid #4d4d4d;
      border-radius: 50%;
      &.active {
        background: #2c70e5;
        border-width: 0;
      }
    }
    .text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 18px;
      color: #3c3c3c;
      line-height: 28px;
      text-align: center;
      font-style: normal;
      text-transform: none;
      margin-left: 10px;
    }
    .line {
      width: 31px;
      height: 31px;
      background: rgba(217, 217, 217, 0.49);
      border-radius: 2px 2px 2px 2px;
      margin-right: 18px;
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      .dot {
        width: 2px;
        height: 2px;
        background: #4e4e4e;
        border-radius: 50%;
      }
      // &::before {
      //   content: "";
      //   position: absolute;
      //   width: 8px;
      //   height: 8px;
      //   background: #4e4e4e;
      //   top: 50%;
      //   left: 50%;
      //   transform: translate(-50%, -50%);
      //   border-radius: 50%;
      // }
      &.active {
        border: 3px solid #2c70e5;
        border-radius: 8px;
      }
    }
    .bg-img {
      width: 82px;
      height: 112px;
      border-radius: 8px;
      object-fit: cover;
      display: flex;
      justify-content: center;
      align-items: center;
      &.active {
        outline: #2c70e5 3px solid;
      }
    }
  }
}

.close {
  color: #aaa;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
input[type="color"] {
  appearance: none; /* 或 -webkit-appearance: none; */
  border: 1px solid #ccc;
  border-radius: 50%;

  padding: 0;
  outline: none;
  box-shadow: none;
}
input[type="color"]:focus {
  outline: none;
  box-shadow: 0 0 3px #0078d7;
}
.custom-color-picker1 {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: v-bind(currentColor1);
  border: 2px solid rgba(255, 255, 255, 0.94);
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.custom-color-picker1 input[type="color"] {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}
.custom-color-picker2 {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: v-bind(currentColor2);
  border: 2px solid rgba(255, 255, 255, 0.94);
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.custom-color-picker2 input[type="color"] {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}
.color-list {
  display: flex;
  align-items: center;
  padding-left: 20px;
  .bg-color {
    width: 29px;
    height: 29px;
    background: #35eda4;
    border-radius: 0px 0px 0px 0px;
    border: 2px solid rgba(255, 255, 255, 0.84);
    margin: 0 -20px;
    border-radius: 50%;
    position: relative;
    z-index: 11;
  }
}
</style>
